package com.bdqn.springsecurity1.config;

import com.bdqn.springsecurity1.filter.ValidCodeFilter;
import com.bdqn.springsecurity1.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class WebSecurityConfig {
    @Autowired
    ValidCodeFilter validCodeFilter;
    @Autowired
    UserService userService;

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
        //如果不想加密就返回
        //return NoOpPasswordEncoder.getInstance();现在版本已经将其移除，淘汰了
    }

    @Bean
    WebSecurityCustomizer webSecurityCustomizer() {
        //忽略这些静态资源（不拦截）
        return (web) -> web.ignoring().requestMatchers("/js/**", "/css/**", "/images/**");
    }

    @Bean
    SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.addFilterBefore(validCodeFilter, UsernamePasswordAuthenticationFilter.class);
        httpSecurity.authorizeHttpRequests()
                .requestMatchers("/", "/index", "/validcode").permitAll()
                .anyRequest().authenticated();
        httpSecurity.formLogin()
                .loginPage("/toLogin")
                .usernameParameter("username")
                .passwordParameter("password")
                .loginProcessingUrl("/login")
                .failureUrl("/toLogin/error")
                .permitAll();
        httpSecurity.logout().logoutSuccessUrl("/index");
        httpSecurity.csrf().disable();
        httpSecurity.exceptionHandling().accessDeniedPage("/errorRole");
        httpSecurity.rememberMe();
        httpSecurity.userDetailsService(userService);
        return httpSecurity.build();
    }
}
